<template>
    <div class="teacherAdd">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="讲师名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        
        <el-form-item label="讲师头衔" prop="level">
        <el-select v-model="ruleForm.level" clearable placeholder="头衔">
          <el-option value="1" label="高级讲师" />
          <el-option value="2" label="首席讲师" />
        </el-select>
      </el-form-item>
        <el-form-item label="资历" prop="intro">
          <el-input type="textarea" v-model="ruleForm.intro" rows="8" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input  v-model="ruleForm.sort"  />
        </el-form-item>
        <el-form-item label="入职时间" prop="joinDate">
          <el-input  v-model="ruleForm.joinDate" />
        </el-form-item>
        <el-form-item label="讲师头像" prop="avatar" >
          <el-upload
          class="avatar-uploader"
          :action="uploadUrl + '/oss/upload-img'"
          :data="{cateDir: 'teacher'}"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script setup lang="ts">
  import { useRoute, useRouter } from "vue-router";
  import { reactive, ref } from "vue";
  import type {
    ComponentSize,
    FormInstance,
    FormRules,
    UploadProps,
  } from "element-plus";
  //导入工具 - 密码校验
  import { checkPass } from "@/assets/js/utils";
  import { ElMessage } from "element-plus";
  import axios from "../../assets/js/axios"
  
  const route = useRoute();
  const router = useRouter();
  //接收传递过来的id
  if (route.query.id) {
    //修改元信息标题
    console.log("id:", route.query.id);
    route.meta.title = "讲师管理 / 讲师编辑";
     // 发送请求显示编辑的信息
     axios
      .get("/serviceedu/edu-teacher/getById/" + route.query.id, {})
      .then((res: any) => {
        console.log(res);
        ruleForm.id = res.data.data.id;
        ruleForm.name = res.data.data.name;
        ruleForm.level = res.data.data.level;
        ruleForm.intro = res.data.data.intro;
        ruleForm.sort = res.data.data.sort;
        ruleForm.joinDate = res.data.data.joinDate;
        imageUrl.value = res.data.data.avatar;
      });
  }
  
  interface RuleForm {
    id?: number,
    level:number,
    name: string;
    intro:string;
    sort:number,
    joinDate:string,
    avatar: string;
  
  }
  
  const formSize = ref("default");
  const ruleFormRef = ref<FormInstance>();
  const ruleForm = reactive<RuleForm>({
    name: "",
    level: 0,
    intro:"",
    sort:0,
    joinDate:"",
    avatar:"",
  });
  
  const rules = reactive<FormRules<RuleForm>>({
    name: [
      { required: true, message: "请输入讲师名", trigger: "blur" },
      { min: 2, max: 20, message: "用户名2-20个字符长度", trigger: "blur" },
    ],
    level: [{ required: true, message: "请输入头衔", trigger: "blur" }],
    intro: [{ required: true, message: "请输入资历", trigger: "blur" }],
    sort:[{ required: true, message: "请输入排序序号", trigger: "blur" }],
    joinDate:[{ required: true, message: "请输入入职时间", trigger: "blur" }],
    avatar: [{ required: true, message: "请选择头像", trigger: "blur" }],
  });
  // 上传头像
  const imageUrl = ref("");
  const uploadUrl = "http://localhost:9001/"
  // 文件上传成功的方法
  const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response
  ) => {
    console.log("response:", response)
    imageUrl.value = response.data.url
    ruleForm.avatar =  response.data.url
  };
  
  //点击保存
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log("submit!", ruleForm);
  
        if (route.query.id) {
          // 进行保存修改
          axios
            .put("/serviceedu/edu-teacher/updateTeacher", ruleForm)
            .then((res: any) => {
              if (res.code === 200) {
                ElMessage({
                  type: "success",
                  message: "修改讲师成功",
                });
                // 跳转列表页
                router.push("/list");
              }
            });
        } else {
          // 进行保存新增
          // 发送axios请求保存用户数据
          axios
            .post("/serviceedu/edu-teacher/addTeacher", ruleForm)
            .then((res: any) => {
              if (res.code === 200) {
                ElMessage({
                  type: "success",
                  message: "保存讲师成功",
                });
                // 跳转列表页
                router.push("/list");
              }
            });
        }
      } else {
        console.log("error submit!", fields);
      }
    });
  };
  
  //点击重置
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
  };
  </script>
  
  <style lang="less" scoped>
  .teacherAdd {
    :deep .avatar-uploader {
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
      .el-upload {
        border: 1px dashed #cccccc;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
      }
      .el-upload:hover {
        border-color: #409eff;
      }
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
  </style>
  